package com.huibao.hulibao.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.widget.ListView;
import android.widget.Toast;

import com.apkfuns.logutils.LogUtils;
import com.huibao.hulibao.R;
import com.huibao.hulibao.adapter.ScanLvAdapter;
import com.huibao.hulibao.constant.GlobalConstants;
import com.huibao.hulibao.entity.LoginEntity;
import com.huibao.hulibao.entity.ResultEntity;
import com.huibao.hulibao.entity.ScanEntity;
import com.huibao.hulibao.entity.ServerEntity;
import com.huibao.hulibao.utils.DialogUtils;
import com.huibao.hulibao.utils.MyUtils;
import com.huibao.hulibao.utils.PreUtils;
import com.huibao.hulibao.utils.T;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;

public class ScanListActivity extends BaseActivity {

    public ServerEntity.ServerDetailData sdd;

    // 扫描返回标识
    public int REQUEST_CODE = 111;
    // 是否结束扫码的标识
    public String finish = "";
    // 是否护理的标识
    public boolean huli = false;

    // 网络请求加载对话框
    private Dialog myDialog;
    public ArrayList<ScanEntity> al_scan;
    public ScanLvAdapter sla;
    public LoginEntity le;
    public String content;
    @BindView(R.id.lv_barCode)
    ListView lv_barCode;

    @OnClick(R.id.iv_back)
    public void back() {
        onBackPressed();
    }


    @PermissionSuccess(requestCode = 105)
    public void doSomething() {
        T.show(getApplicationContext(), "相机权限已开启", 0);
        Intent intent = new Intent(ScanListActivity.this, CaptureActivity.class);
        startActivityForResult(intent, REQUEST_CODE);

    }

    @PermissionFail(requestCode = 105)
    public void doFailSomething() {
        T.show(getApplicationContext(), "相机权限打开失败！", 0);
    }

    @OnClick(R.id.tv_scan)
    public void scan() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            // 请求开启相机权限
            PermissionGen.needPermission(this, 105,
                    new String[]{
                            Manifest.permission.CAMERA}
            );
        } else {
            Intent intent = new Intent(ScanListActivity.this, CaptureActivity.class);
            startActivityForResult(intent, REQUEST_CODE);
        }
    }

    public void showDialog() {
        myDialog = DialogUtils.createLoadingDialog(ScanListActivity.this, getResources().getString(R.string.jiazaizhong));
    }

    public void closeDialog() {
        DialogUtils.closeDialog(myDialog);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan_list);
        ButterKnife.bind(this);
        le = (LoginEntity) PreUtils.getObject(getApplicationContext(), "LoginEntity");
        sdd = (ServerEntity.ServerDetailData) getIntent().getSerializableExtra("ServerDetailData");
        content = getIntent().getStringExtra("content");
        al_scan = (ArrayList<ScanEntity>) getIntent().getSerializableExtra("Huli");
        huli = getIntent().getBooleanExtra("boolean_Huli", false);

        // 开始护理的二维码逻辑处理
        if (al_scan == null) {
            // 处理计划任务扫码的逻辑
            if (sdd == null) {
                return;
            }
            finish = getIntent().getStringExtra("finish");

            al_scan = new ArrayList<>();
            if (finish == null || finish.equals("")) {
                initStartData();
            } else {
                initFinishData();
            }
        } else {
            sla = new ScanLvAdapter(al_scan, getApplicationContext());
            lv_barCode.setAdapter(sla);
        }


    }

    // 结束扫码的初始化
    public void initFinishData() {
        String endScanLabel = sdd.ServeEndScanLabel;

        if (endScanLabel.contains(";")) {
            String[] arr = endScanLabel.split(";");
            for (int i = 0; i < arr.length; i++) {
                ScanEntity se = new ScanEntity();
                se.setScanLabel(arr[i]);
                se.setServeId(sdd.TaskId);
                al_scan.add(se);
            }
        } else {
            ScanEntity se = new ScanEntity();
            se.setScanLabel(endScanLabel);
            se.setServeId(sdd.TaskId);
            al_scan.add(se);
        }

        sla = new ScanLvAdapter(al_scan, getApplicationContext());
        lv_barCode.setAdapter(sla);
    }

    // 开始扫码的初始化
    public void initStartData() {
        String startScanLabel = sdd.ServeStartScanLabel;

        if (startScanLabel.contains(";")) {
            String[] arr = startScanLabel.split(";");
            for (int i = 0; i < arr.length; i++) {
                ScanEntity se = new ScanEntity();
                se.setScanLabel(arr[i]);
                se.setServeId(sdd.TaskId);
                al_scan.add(se);
            }
        } else {
            ScanEntity se = new ScanEntity();
            se.setScanLabel(startScanLabel);
            se.setServeId(sdd.TaskId);
            al_scan.add(se);
        }

        sla = new ScanLvAdapter(al_scan, getApplicationContext());
        lv_barCode.setAdapter(sla);

    }

    // 是否全部校验成功
    public boolean isAllCheckOk() {
        boolean b = true;
        for (int i = 0; i < al_scan.size(); i++) {
            ScanEntity se = al_scan.get(i);
            if (se.isScan() == false) {
                b = false;
            }
        }
        return b;
    }

    // 校验全部成功后将该任务状态改为执行中记录在本地和时间
    public void saveStatus() {
        String str = (String) PreUtils.getParam(getApplicationContext(), "RenWuStatus", "");
        if (str.equals("")) {
            StringBuffer sb = new StringBuffer();
            sb.append(sdd.TaskId).append("@").append(MyUtils.getFormatTimeToString(System.currentTimeMillis()));
            PreUtils.setParam(getApplicationContext(), "RenWuStatus", sb.toString());
        } else {
            if (!str.contains(sdd.TaskId)) {
                PreUtils.setParam(getApplicationContext(), "RenWuStatus", str + "," + sdd.TaskId + "@" + MyUtils.getFormatTimeToString(System.currentTimeMillis()));
            }
        }
    }

    // 任务结束后清除本地记录的状态信息
    public void clearStatus() {
        String str = (String) PreUtils.getParam(getApplicationContext(), "RenWuStatus", "");
        // 10696@2018-11-10 20:10:39,10707@2018-11-10 21:32:10,10709@2018-11-10 21:45:11
        if (str.contains(",")) {
            String[] arr = str.split(",");
            for (int i = 0; i < arr.length; i++) {
                if (arr[i].contains(sdd.TaskId)) {
                    arr[i] = "";
                }
            }

            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < arr.length; i++) {
                if (!arr[i].equals("")) {
                    if (i == arr.length - 1) {
                        sb.append(arr[i]);
                    } else {
                        sb.append(arr[i]).append(",");
                    }
                }
            }

            PreUtils.setParam(getApplicationContext(), "RenWuStatus", sb.toString());

        } else {
            PreUtils.setParam(getApplicationContext(), "RenWuStatus", "");
        }

    }

    // 结束任务请求
    public void finishRenwuToServer(String stime) {
        String etime = MyUtils.getFormatTimeToString(System.currentTimeMillis()).replace(":", "%3A");
        if (le == null) {
            return;
        }
        RequestParams params = new RequestParams(GlobalConstants.URL);
        params.setCacheMaxAge(0);
        showDialog();
        JSONObject object = new JSONObject();
        try {
            object.put("taskid", sdd.TaskId);
            object.put("stime", stime.replace(":", "%3A"));
            object.put("etime", etime);
            object.put("clue", content);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        params.addBodyParameter("q", le.Message.Session + GlobalConstants.URL_RENWU_FINISH + object.toString());
        LogUtils.d("params = " + params.toString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                closeDialog();
                // 清除本地记录状态
                clearStatus();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(result);
                    LogUtils.d("result = " + jsonObject.toString());
                    ResultEntity re = GlobalConstants.gson.fromJson(jsonObject.toString(), ResultEntity.class);
                    if (re != null && re.State.equals(GlobalConstants.SUCCESS_CODE)) {
                        T.show(getApplicationContext(), getString(R.string.renwujieshuchenggong), 0);
                        Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                        startActivity(intent);
                        finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                closeDialog();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                closeDialog();
            }

            @Override
            public void onFinished() {
                closeDialog();
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    // 校验数据并设置属性
                    // 判断该次扫码是否有效
                    boolean b = false;
                    for (int i = 0; i < al_scan.size(); i++) {
                        ScanEntity se = al_scan.get(i);
                        if (result.equals(se.getScanLabel().split(":")[1])) {
                            b = true;
                            se.setScan(true);
                        }
                    }

                    // 判断该次扫码是否有效
                    if (!b) {
                        T.show(getApplicationContext(), "扫码无效", 0);
                    }


                    lv_barCode.setAdapter(sla);
                    if (isAllCheckOk()) {
                        T.show(getApplicationContext(), "全部校验通过", 0);
                        if (huli) {
                            setResult(3);
                            finish();
                        } else {
                            if (finish == null || finish.equals("")) {
                                // 将状态记录到本地数据
                                saveStatus();
                                String stime = MyUtils.getFormatTimeToString(System.currentTimeMillis());
                                Intent intent = new Intent(getApplicationContext(), ServerFinishActivity.class);
                                intent.putExtra("title", sdd.ServeName);
                                // 结束任务需要用到的参数
                                intent.putExtra("TaskId", sdd.TaskId);
                                intent.putExtra("stime", stime);
                                intent.putExtra("ServerDetailData", sdd);
                                intent.putExtra("zhixinzhong", "zhixinzhong");
                                startActivity(intent);
                            } else {
                                String str = (String) PreUtils.getParam(getApplicationContext(), "RenWuStatus", "");
                                // 10696@2018-11-10 20:10:39,10707@2018-11-10 21:32:10,10709@2018-11-10 21:45:11
                                if (str == null || str.equals("")) {
                                    return;
                                }
                                if (str.contains(",")) {
                                    String[] arr = str.split(",");
                                    String stime = "";
                                    for (int i = 0; i < arr.length; i++) {
                                        if (arr[i].contains(sdd.TaskId)) {
                                            stime = arr[i].split("@")[1];
                                        }
                                    }
                                    // 结束任务
                                    finishRenwuToServer(stime);
                                } else {
                                    finishRenwuToServer(str.split("@")[1]);
                                }
                            }
                        }
                    }

                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(ScanListActivity.this, "解析二维码失败", Toast.LENGTH_LONG).show();
                }
            }
        }
    }
}
